package com.dpwgc.provider.interceptor;

import com.alibaba.fastjson.JSON;
import com.dpwgc.provider.utils.RedisUtil;
import com.dpwgc.provider.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * 登录验证拦截
 */
@Controller
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String uuid = request.getHeader("uuid");
        String token = request.getHeader("token");

        ResultUtil resultUtil = new ResultUtil();

        if (uuid==null){
            resultUtil.setMsg("请登陆后访问");
            resultUtil.setCode(440);
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(resultUtil));
            writer.flush();
            return false;
        }

        Object resToken = redisUtil.get(uuid);
        String strToken = String.valueOf(resToken);

        if (strToken.equals(token)){
            return true;
        }else {
            resultUtil.setMsg("请登陆后访问");
            resultUtil.setCode(440);
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(resultUtil));
            writer.flush();
            return false;
        }
    }
}
